<!-- 规格信息 -->
<template>
  <el-row :gutter="10">
    <el-col :span="10">
      <el-form-item label="库存：" prop="stock_total">
        <el-input v-model.number="form.stock_total" :disabled="form.sku_list.length !== 0" maxlength="8" placeholder="请输入库存"></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="10">
      <el-form-item label="已售基数：" prop="sales_initial">
        <el-input v-model.number="form.sales_initial" maxlength="6" placeholder="请输入已售基数"></el-input>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="10" v-for="(item, index) in spec_list" :key="item.id">
    <el-col :span="20">
      <el-form-item :label="item.name + ':'">
        <div class="tag-info-box">
          <div class="tag-info" :key="tag.id" v-for="tag in item.spec_value">
            <el-tag closable size="large" type="primary" :disable-transitions="false" @dblclick="handleOndblclick(index, item.id, tag.id, tag.name)" @close="handleClose(index, item.id, tag.id)">
              {{ tag.name }}
            </el-tag>
          </div>
          <el-input class="input-new-tag" v-if="item.inputVisible" v-model="item.inputValue" @keyup.enter="handleInputConfirm(index, item.id, item.inputValue)" @blur="handleInputConfirm(index, item.id, item.inputValue)"></el-input>
          <el-button v-else class="button-new-tag" @click="showInput(index)">+ 新增</el-button>
          <el-icon :size="16" @click="handleDeleteSpecName(item.id)" class="cursor"><CircleClose /></el-icon>
          <el-tooltip placement="top" content="双击规格值可修改规格值名称">
            <el-icon class="icon-wzg-config">
              <InfoFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="10" v-show="showSpecName">
    <el-col :span="8">
      <el-form-item label="规格名：">
        <el-input v-model.trim="spec.name" placeholder="请输入规格名"></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="5">
      <el-button type="primary" :disabled="disabledbtn" @click="handleConfirmSpecName">确认</el-button>
      <el-button type="primary" plain :disabled="disabledbtn" @click="handleCancelSpecName">取消</el-button>
    </el-col>
  </el-row>
  <el-row :gutter="10" v-show="!showSpecName && spec_list.length < 2">
    <el-col :span="10">
      <el-form-item label="">
        <el-button type="primary" plain @click="handleAddSpecName">添加规格</el-button>
      </el-form-item>
    </el-col>
  </el-row>

  <el-row :gutter="10" v-show="form.sku_list.length > 0">
    <el-col :span="10">
      <el-form-item label="">
        <el-button type="primary" plain @click="handleBatchSetUpSpecInfo">批量设置</el-button>
      </el-form-item>
    </el-col>
  </el-row>

  <el-row :gutter="10">
    <el-col :span="20">
      <el-form-item label="商品规格：">
        <el-table :data="form.sku_list" border class="table" :reserve-selection="true">
          <el-table-column :prop="'w' + item.id" :label="item.name" align="center" v-for="item in spec_list" :key="item.id"> </el-table-column>
          <el-table-column prop="goods_sku_no" label="规格货号" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.goods_sku_no" placeholder="请输入规格货号"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="cost_price" label="成本价" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.cost_price" placeholder="请输入成本价"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="wholesale_price" label="批发价" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.wholesale_price" placeholder="请输入批发价"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="retail_price" label="零售价" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.retail_price" placeholder="请输入零售价"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="official_price" label="淘宝价" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.official_price" placeholder="请输入淘宝价"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="red_packet_price" label="最多可抵扣红包" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.red_packet_price" placeholder="请输入最多可抵扣红包"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="stock_num" label="库存" align="center">
            <template #default="scope: { row: ISku }">
              <el-input v-model.trim.number="scope.row.stock_num" placeholder="请输入库存" @change="handleChangeStockNum"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="image" label="图片(默认为主图)" align="center" width="150">
            <template #default="scope: { row: ISku }">
              <UploadImageInfo suggestInfo="" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="scope.row" isCenter />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 批量设置规格信息弹出框 -->
  <el-dialog title="批量设置" v-model="editVisible" width="60%" draggable @closed="closedFormDialog">
    <el-form ref="spacBatchInfoRef" :model="spacBatchInfo" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="成本价：" prop="cost_price">
            <el-input v-model.trim="spacBatchInfo.cost_price" placeholder="成本价"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="批发价：" prop="wholesale_price">
            <el-input v-model.trim="spacBatchInfo.wholesale_price" placeholder="批发价"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="零售价：" prop="retail_price">
            <el-input v-model.trim="spacBatchInfo.retail_price" placeholder="零售价"> </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="淘宝价：" prop="official_price">
            <el-input v-model.trim.number="spacBatchInfo.official_price" placeholder="淘宝价"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="最多可抵扣红包：" prop="red_packet_price">
            <el-input v-model.trim.number="spacBatchInfo.red_packet_price" placeholder="最多可抵扣红包"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="库存：" prop="sort">
            <el-input v-model.trim.number="spacBatchInfo.stock_num" placeholder="库存"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancelSubmit">取 消</el-button>
        <el-button type="primary" :disabled="disabledbtn" @click="handleSubmitForm">确 定 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 设置规格名称弹出框 -->
  <el-dialog title="修改规格值名称" v-model="spaceValueVisible" width="40%" @closed="closedSpaceValueFormDialog">
    <el-form ref="spaceValueObjRef" :model="spaceValueObj" :rules="rules" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="20">
          <el-form-item label="规格值名称：" prop="name">
            <el-input v-model.trim="spaceValueObj.name" placeholder="规格值名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="spaceValueVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateSpaceValue">确 定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import type { IMallGoodsDetail, ISku } from "@/types/redPacketMallManage/mallGoods";
import type { IAddSpec, IAddSpecValue, IAddSpecValueVO, IAddSpecVO, IBatchSpecEditParams, IInputSpecName, ISpecItem, ISpecValueDTO } from "@/types/redPacketMallManage/spec";
import { commonMallSKUInfo, postSpecValueInfo } from "@/utils/api/mallSKU";
import { ElMessageBox } from "element-plus";
interface Props {
  toggleState: (state: boolean) => void;
  specList: ISpecItem[];
}
const { toggleState, specList } = defineProps<Props>();
const form = defineModel<IMallGoodsDetail>("form", { required: true });
const disabledbtn = defineModel<boolean>("disabledbtn", { required: true });
const loading = defineModel<boolean>("loading", { required: true });

/* 规格名称相关显示或隐藏 */
const showSpecName = ref<boolean>(false);
const editVisible = ref<boolean>(false);
const spaceValueVisible = ref<boolean>(false);
const spec_list = ref<ISpecItem[]>([]);

const spec = reactive<IInputSpecName>({
  name: ""
});
const spacBatchInfoRef = useTemplateRef("spacBatchInfoRef");
const spaceValueObjRef = useTemplateRef("spaceValueObjRef");

const rules = reactive({
  name: [{ required: true, message: "请填写规格名称", trigger: "blur" }]
});

/* 批量修改规格信息 */
const spacBatchInfo = reactive<IBatchSpecEditParams>({
  stock_num: 0,
  retail_price: "",
  official_price: "",
  red_packet_price: "",
  wholesale_price: "",
  cost_price: ""
});
/* 修改的规格值信息 */
const spaceValueObj = reactive<ISpecValueDTO>({
  id: 0,
  index: 0,
  spec_list_id: 0,
  name: ""
});

// 暴露属性给父组件
defineExpose({
  spec_list
});

watch(
  () => specList,
  newValue => {
    spec_list.value = newValue;
  }
);
/* 添加规格名称 */
function handleAddSpecName() {
  if (spec_list.value.length > 0 && spec_list.value[0].spec_value.length === 0) {
    ElMessage.warning(`请先填写${spec_list.value[0].name}的规格值`);
    return;
  }
  showSpecName.value = true;
}

/* 删除某个 规格值 */
function handleClose(index: number, spec_list_id: number, id: number) {
  ElMessageBox.confirm("规格值删除后无法取消，确认删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      /* 删除规格组中对应的规格值信息 */
      for (let i = 0; i < spec_list.value[index].spec_value.length; i++) {
        if (spec_list.value[index].spec_value[i].id === id) {
          spec_list.value[index].spec_value.splice(i, 1);
          break;
        }
      }
      /* 记录规格组中还有几条规格值 */
      let num = spec_list.value[index].spec_value.length;

      /* 如果是多个规格，需要 先取出来，通过_截取，转成数组，判断是否在数组中，在就删除数组中的数据，让后在 _ join成字符串，最好赋值给自己*/
      let i = form.value.sku_list.length;
      while (i--) {
        let tempList = form.value.sku_list[i].goods_sku_id.split("_");
        if (tempList.includes(id + "")) {
          if (tempList.length === 1 || num > 0) {
            form.value.sku_list.splice(i, 1);
          } else {
            tempList.splice(tempList.indexOf(id + ""), 1);
            /* 当前只有两个，可以直接赋值，多个就 join*/
            form.value.sku_list[i].goods_sku_id = tempList.join("_");
            form.value.sku_list[i]["w" + spec_list_id] = "";
          }
        }
      }
      /* 如果所有的规格都删除了，并且规格组还有两个以上，那么就只留第一个规格组信息 */
      if (form.value.sku_list.length === 0 && spec_list.value.length > 1) {
        spec_list.value = [spec_list.value[0]];
      }
      handleChangeStockNum();
      ElMessage.success("删除成功!");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}
/* 修改规格数量 事件 */
function handleChangeStockNum() {
  let num = 0;
  for (let i = 0; i < form.value.sku_list.length; i++) {
    num += form.value.sku_list[i].stock_num;
  }
  form.value.stock_total = num;
}

/* 点击新增tag标签 */
function showInput(index: number) {
  spec_list.value[index].inputVisible = true;
  // $nextTick(() => {
  //   $refs[refs].$refs.input.focus();
  // });
  // $refs[refs].$refs.input.focus();
}

/* 删除规格名称 */
function handleDeleteSpecName(id: number) {
  ElMessageBox.confirm("规格名删除后无法取消，确认删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      ElMessage.success("删除成功!");
      /* 删除的规格值id */
      let specValueList = [];
      /* 删除规格组信息 */
      for (let i = 0; i < spec_list.value.length; i++) {
        if (spec_list.value[i].id == id) {
          /* 存储得到对应的规格值ID */
          for (let j = 0; j < spec_list.value[i].spec_value.length; j++) {
            specValueList.push(spec_list.value[i].spec_value[j].id);
          }
          spec_list.value.splice(i, 1);
          break;
        }
      }
      /* 如果只有一个规格组，就直接匹配删除 所有规格列表信息即可 */
      if (spec_list.value.length === 0) {
        form.value.sku_list = [];
        return;
      }
      // let list = [];
      /* 当前要删除的规格组中 一个规格的时候，直接修改数据， 两个规格的时候*/
      /* 如果是多个规格，需要 先取出来，通过_截取，转成数组，判断是否在数组中，在就删除数组中的数据，然后在 _ join 转成字符串，最后赋值给自己*/
      for (let i = 0; i < form.value.sku_list.length; i++) {
        let tempList = form.value.sku_list[i].goods_sku_id.split("_");
        for (let j = 0; j < specValueList.length; j++) {
          const _id = specValueList[j] + "";
          if (tempList.includes(_id)) {
            tempList.splice(tempList.indexOf(_id), 1);
            /* 当前只有两个，可以直接赋值，多个就 join*/
            form.value.sku_list[i].goods_sku_id = tempList.join("_");
            break;
          }
        }
      }
      let list = [];
      /* 此时 去重即可 */
      for (let i = 0; i < form.value.sku_list.length; i++) {
        const element = form.value.sku_list[i].goods_sku_id;
        if (list.length === 0) {
          list.push(JSON.parse(JSON.stringify(form.value.sku_list[i])));
        } else {
          let _boolean = false;
          for (let k = 0; k < list.length; k++) {
            let sku_id = list[k].goods_sku_id;
            if (element == sku_id) {
              _boolean = false;
              break;
            } else {
              _boolean = true;
            }
          }
          if (_boolean) {
            list.push(JSON.parse(JSON.stringify(form.value.sku_list[i])));
          }
        }
      }
      /* 删除所有的规格组id对应的属性名 */
      let i = list.length;
      while (i--) {
        if (list[i]["w" + id] !== undefined) {
          /* 删除对象中的属性  'w'+id */
          delete list[i]["w" + id];
        }
      }
      form.value.sku_list = list;
      handleChangeStockNum();
      /* 需要删除 sku_list 中的数据 ，倒删除*/
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

/* 校验规格值信息 */
function handleCheckSpecValueName(index: number, inputValue: string) {
  if (inputValue === "") {
    spec_list.value[index].inputVisible = false;
    return false;
  }
  for (let i = 0; i < spec_list.value[index].spec_value.length; i++) {
    if (spec_list.value[index].spec_value[i].name === spec_list.value[index].inputValue) {
      ElMessage.warning("请填写不同的规格值");
      return false;
    }
  }
  return true;
}
/* 失去焦点和enter事件，创建tag标签 */
function handleInputConfirm(index: number, spec_id: number, inputValue: string) {
  if (disabledbtn.value) return;
  if (!handleCheckSpecValueName(index, inputValue)) return;
  handlePostSpecValueInfo(index, spec_id, spec_list.value[index].inputValue);
}

/* 保存规格值 */
function handlePostSpecValueInfo(index: number, spec_id: number, spec_value: string) {
  toggleState(true);
  postSpecValueInfo<IAddSpecValueVO, IAddSpecValue>({ spec_id, spec_value })
    .then(res => {
      handleSKUList(index, spec_id, spec_value, res.result, res.result.id);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 规格sku列表的修改 */
function handleSKUList(index: number, spec_id: number, spec_value: string, data: IAddSpecValueVO, goods_sku_id: number) {
  spec_list.value[index].spec_value.push({
    id: goods_sku_id,
    name: spec_value,
    sort: data.sort
  });
  spec_list.value[index].inputVisible = false;
  spec_list.value[index].inputValue = "";

  /* 创建规格信息 */
  /* 如果没有规格，就直接新增，如果有规格就需要编辑或 编辑+新增了 */
  /* goods_sku_id 需要组合 */
  let skuObj: ISku = {
    id: 0,
    /* 对象的属性不能是数字，所以需要把他改成字符串 */
    /* 用规格id做属性名，用规格值做属性值 */
    ["w" + spec_id]: spec_value,
    goods_sku_id: goods_sku_id + "" /* 1_2_3 */,
    goods_sku_no: "",
    image: "",
    cost_price: form.value.cost_price,
    wholesale_price: form.value.wholesale_price,
    retail_price: form.value.retail_price,
    official_price: form.value.official_price,
    red_packet_price: form.value.red_packet_price,
    stock_num: 0
  };

  /* 一组规格 直接push */
  // debugger;
  if (spec_list.value.length === 1) {
    form.value.sku_list.push(skuObj);
    handleChangeStockNum();
    return;
  }
  if (spec_list.value[0].spec_value.length === 1 || spec_list.value[1].spec_value.length === 1) {
    let skuIdListlength = form.value.sku_list[0].goods_sku_id.split("_").length;
    if (skuIdListlength === 1) {
      /* 修改 goods_sku_id 需要以下划线的方式连接*/
      for (let i = 0; i < form.value.sku_list.length; i++) {
        const temp = form.value.sku_list[i].goods_sku_id;
        if (index === 0) {
          form.value.sku_list[i].goods_sku_id = goods_sku_id + "_" + temp;
        } else {
          form.value.sku_list[i].goods_sku_id = temp + "_" + goods_sku_id;
        }
        form.value.sku_list[i]["w" + spec_id] = spec_value;
      }
    } else {
      /* 新增 */
      for (let i = 0; i < spec_list.value.length; i++) {
        const element = spec_list.value[i];
        if (i !== index) {
          for (let j = 0; j < spec_list.value[i].spec_value.length; j++) {
            const temp = spec_list.value[i].spec_value[j];
            let tepm_goods_sku_id = "";
            if (index === 0) {
              tepm_goods_sku_id = goods_sku_id + "_" + temp.id;
            } else {
              tepm_goods_sku_id = temp.id + "_" + goods_sku_id;
            }
            let skuObj: ISku = {
              id: 0,
              /* 对象的属性不能是数字，所以需要把他改成字符串 */
              /* 用规格id做属性名，用规格值做属性值 */
              ["w" + element.id]: temp.name,
              ["w" + spec_id]: spec_value,
              goods_sku_id: tepm_goods_sku_id,
              goods_sku_no: "",
              image: "",
              cost_price: form.value.cost_price,
              wholesale_price: form.value.wholesale_price,
              retail_price: form.value.retail_price,
              official_price: form.value.official_price,
              red_packet_price: form.value.red_packet_price,
              stock_num: 0
            };
            form.value.sku_list.push(skuObj);
          }
        }
      }
    }

    /* 按照规格组1中的数据进行排序，排序 */
    handleSortList(form.value.sku_list);
    handleChangeStockNum();
    return;
  }

  /* 新增 */
  for (let i = 0; i < spec_list.value.length; i++) {
    const element = spec_list.value[i];
    if (i !== index) {
      for (let j = 0; j < spec_list.value[i].spec_value.length; j++) {
        const temp = spec_list.value[i].spec_value[j];
        let tepm_goods_sku_id = "";
        if (index === 0) {
          tepm_goods_sku_id = goods_sku_id + "_" + temp.id;
        } else {
          tepm_goods_sku_id = temp.id + "_" + goods_sku_id;
        }
        let skuObj: ISku = {
          id: 0,
          /* 对象的属性不能是数字，所以需要把他改成字符串 */
          /* 用规格id做属性名，用规格值做属性值 */
          ["w" + element.id]: temp.name,
          ["w" + spec_id]: spec_value,
          goods_sku_id: tepm_goods_sku_id,
          goods_sku_no: "",
          image: "",
          cost_price: form.value.cost_price,
          wholesale_price: form.value.wholesale_price,
          retail_price: form.value.retail_price,
          official_price: form.value.official_price,
          red_packet_price: form.value.red_packet_price,
          stock_num: 0
        };

        form.value.sku_list.push(skuObj);
      }
    }
  }
  /* 按照规格组1中的数据进行排序，排序 */
  handleSortList(form.value.sku_list);
  handleChangeStockNum();
}

/* 数组排序 */
function handleSortList(list: ISku[]) {
  list.sort(function (arr1: ISku, arr2: ISku) {
    return Number(arr1.goods_sku_id.split("_")[0]) - Number(arr2.goods_sku_id.split("_")[0]);
  });
}
/* 确认添加规格名称信息 */
function handleConfirmSpecName() {
  for (let i = 0; i < spec_list.value.length; i++) {
    if (spec_list.value[i].name === spec.name) {
      ElMessage.warning("请填写不同的规格名称");
      return;
    }
  }
  showSpecName.value = false;

  /* 请求保存规格名称 */
  handleCommonMallSKUInfo(spec.name);
}
/* 保存规格名称 */
function handleCommonMallSKUInfo(spec_name: string) {
  toggleState(true);
  commonMallSKUInfo<IAddSpecVO, IAddSpec>({ spec_name })
    .then(res => {
      spec_list.value.push({
        id: res.result.id,
        name: spec.name,
        inputVisible: false,
        inputValue: "",
        spec_value: []
      });
      spec.name = "";
      handleCancelSpecName();
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 取消添加规格名称信息 */
function handleCancelSpecName() {
  showSpecName.value = false;
}
/* 批量设置规格信息 */
function handleBatchSetUpSpecInfo() {
  editVisible.value = true;
  spacBatchInfo.retail_price = form.value.retail_price;
  spacBatchInfo.official_price = form.value.official_price;
  spacBatchInfo.red_packet_price = form.value.red_packet_price;
  spacBatchInfo.wholesale_price = form.value.wholesale_price;
  spacBatchInfo.cost_price = form.value.cost_price;
}

/* 关闭新增编辑查看 弹出框事件 */
function closedFormDialog() {
  spacBatchInfo.stock_num = 0;
  spacBatchInfo.retail_price = "";
  spacBatchInfo.official_price = "";
  spacBatchInfo.red_packet_price = "";
  spacBatchInfo.wholesale_price = "";
  spacBatchInfo.cost_price = "";

  spacBatchInfoRef.value?.clearValidate();
}

/* 取消批量设置弹框 */
function handleCancelSubmit() {
  editVisible.value = false;
}

/* 批量设置规格信息 */
function handleSubmitForm() {
  for (let i = 0; i < form.value.sku_list.length; i++) {
    // form.value.sku_list[i].stock_num = spacBatchInfo.stock_num;
    form.value.sku_list[i].retail_price = spacBatchInfo.retail_price;
    form.value.sku_list[i].official_price = spacBatchInfo.official_price;
    form.value.sku_list[i].red_packet_price = spacBatchInfo.red_packet_price;
    form.value.sku_list[i].wholesale_price = spacBatchInfo.wholesale_price;
    form.value.sku_list[i].cost_price = spacBatchInfo.cost_price;
    form.value.sku_list[i].stock_num = spacBatchInfo.stock_num;
  }
  /* 批量设置库存 */
  form.value.stock_total = form.value.sku_list.length * spacBatchInfo.stock_num;
  handleCancelSubmit();
}

/* 双击打开模态框 */
function handleOndblclick(index: number, spec_list_id: number, id: number, name: string) {
  spaceValueVisible.value = true;
  spaceValueObj.index = index;
  spaceValueObj.spec_list_id = spec_list_id;
  spaceValueObj.id = id;
  spaceValueObj.name = name;
}

/* 关闭规格值修改 弹出框事件 */
function closedSpaceValueFormDialog() {
  spaceValueObj.index = 0;
  spaceValueObj.spec_list_id = 0;
  spaceValueObj.id = 0;
  spaceValueObj.name = "";
  spaceValueObjRef.value?.clearValidate();
}

/* 校验不同的规格值 */
function handleCheckDialogSpecValueName(index: number, id: number, name: string) {
  if (name === "") {
    spec_list.value[index].inputVisible = false;
    return false;
  }
  for (let i = 0; i < spec_list.value[index].spec_value.length; i++) {
    if (spec_list.value[index].spec_value[i].id !== id && spec_list.value[index].spec_value[i].name === name) {
      ElMessage.warning("请填写不同的规格值");
      return false;
    }
  }
  return true;
}

/* 修改规格值 */
function handleUpdateSpaceValue() {
  if (!spaceValueObjRef.value) return;
  spaceValueObjRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleCheckDialogSpecValueName(spaceValueObj.index, spaceValueObj.id, spaceValueObj.name)) return;
    for (let i = 0; i < spec_list.value[spaceValueObj.index].spec_value.length; i++) {
      if (spec_list.value[spaceValueObj.index].spec_value[i].id === spaceValueObj.id) {
        spec_list.value[spaceValueObj.index].spec_value[i].name = spaceValueObj.name;
        break;
      }
    }
    for (let i = 0; i < form.value.sku_list.length; i++) {
      if (form.value.sku_list[i].goods_sku_id.split("_").includes("" + spaceValueObj.id)) {
        form.value.sku_list[i]["w" + spaceValueObj.spec_list_id] = spaceValueObj.name;
      }
    }
    let flag = true;
    for (let i = 0; i < form.value.update_specs!.length; i++) {
      if (form.value.update_specs![i].id === spaceValueObj.id) {
        form.value.update_specs![i].name = spaceValueObj.name;
        flag = false;
      }
    }
    if (flag) {
      form.value.update_specs!.push({
        id: spaceValueObj.id,
        name: spaceValueObj.name
      });
    }
    spaceValueVisible.value = false;
  });
}
</script>

<style lang="scss" scoped>
.gap10 {
  gap: 10px;
}

.tag-info-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  flex: 1;
}
.button-new-tag {
  height: 28px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}
.ml10 {
  margin-left: 10px;
}
.cursor {
  cursor: pointer;
}

/* 底部按钮居中 */
.dialog-footer {
  margin: 10px 0;
  text-align: center;
}
</style>
